


<!DOCTYPE html>
<html lang="zh-CN">
  <head><meta name="generator" content="Hexo 3.8.0">
    <title>Vue 组件的单元测试 — Vue.js</title>
    <meta charset="utf-8">
    <meta name="description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="alternate" hreflang="x-default" href="https://vuejs.org/v2/cookbook/unit-testing-vue-components.html">
    <link rel="alternate" hreflang="zh" href="unit-testing-vue-components.html">
    <link rel="alternate" hreflang="ja" href="https://jp.vuejs.org/v2/cookbook/unit-testing-vue-components.html">
    <link rel="alternate" hreflang="ru" href="https://ru.vuejs.org/v2/cookbook/unit-testing-vue-components.html">
    <link rel="alternate" hreflang="ko" href="https://kr.vuejs.org/v2/cookbook/unit-testing-vue-components.html">
    <link rel="alternate" hreflang="pt-BR" href="https://br.vuejs.org/v2/cookbook/unit-testing-vue-components.html">
    <link rel="alternate" hreflang="fr" href="https://fr.vuejs.org/v2/cookbook/unit-testing-vue-components.html">

    <meta property="og:type" content="article">
    <meta property="og:title" content="Vue 组件的单元测试 — Vue.js">
    <meta property="og:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta property="og:image" content="https://cn.vuejs.org//images/logo.png">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Vue 组件的单元测试 — Vue.js">
    <meta name="twitter:description" content="Vue.js - The Progressive JavaScript Framework">
    <meta name="twitter:image" content="https://cn.vuejs.org/images/logo.png">

    <link rel="apple-touch-icon" sizes="57x57" href="../../images/icons/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="../../images/icons/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="../../images/icons/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="../../images/icons/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="../../images/icons/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="../../images/icons/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="../../images/icons/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="../../images/icons/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="../../images/icons/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="../../images/icons/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="../../images/icons/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="../../images/icons/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="../../images/icons/favicon-16x16.png">
    <meta name="msapplication-TileImage" content="/images/icons/ms-icon-144x144.png">
    <link rel="icon" href="../../images/logo.png" type="image/png">

    <meta name="msapplication-TileColor" content="#4fc08d">
    <meta name="theme-color" content="#4fc08d">

    <meta name="msapplication-config" content="browserconfig.xml">
    <link rel="manifest" href="../../manifest.json">

    <!-- <link href="https://fonts.googleapis.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin> -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com" rel="preconnect" crossorigin> -->

    <!-- <link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'> -->
    <!-- <link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'> -->

    <link href="https://code.bdstatic.com/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <!-- main page styles -->
    <link rel="stylesheet" href="../../css/page.css">

    <!-- this needs to be loaded before guide's inline scripts -->
    <script src="../../js/vue.js"></script>

    

    <script>
      Vue.config.productionTip = false
      window.PAGE_TYPE = "cookbook"
    </script>

    <!-- ga -->
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-46852172-3', 'cn.vuejs.org');
      ga('send', 'pageview');
    </script>
  </head>
  <body class="docs">
    <div id="mobile-bar">
      <a class="menu-button"></a>
      <a class="logo" href="../../index.html"></a>
    </div>
    <div id="header">
  <a id="logo" href="../../index.html">
    <img src="../../images/logo.png" alt="vue logo">
    <span>Vue.js</span>
  </a>
  <ul id="nav">
    <li>
  <form id="search-form">
    <input type="text" id="search-query-nav" class="search-query st-default-search-input" aria-label="搜索">
  </form>
</li>
<li class="nav-dropdown-container learn">
  <a class="nav-link current">学习</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>文档</h4></li>
    <li>
      <ul>
        <li><a href="../guide/index.html" class="nav-link">教程</a></li>
        <li><a href="../api/index.html" class="nav-link">API</a></li>
        <li><a href="../style-guide/index.html" class="nav-link">风格指南</a></li>
        <li><a href="../examples/index.html" class="nav-link">示例</a></li>
        <li><a href="index.html" class="nav-link current">Cookbook</a></li>
      </ul>
    </li>
    <li><h4>视频教程</h4></li>
    <li>
      <ul>
        <li><a href="https://www.vuemastery.com/courses/" class="nav-link" target="_blank" rel="sponsored noopener">Vue Mastery (英文)</a></li>
        <li><a href="https://vueschool.io/?friend=vuejs&amp;utm_source=Vuejs.org&amp;utm_medium=Link&amp;utm_content=Navbar%20Dropdown" class="nav-link" target="_blank" rel="noopener">Vue School (英文)</a></li>
        <li><a href="https://learning.dcloud.io/" class="nav-link" target="_blank" rel="sponsored noopener">DCloud 视频教程</a></li>
      </ul>
    </li>
  </ul>
</li>

<li class="nav-dropdown-container ecosystem">
  <a class="nav-link">生态系统</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><h4>帮助</h4></li>
    <li><ul>
      <li><a href="https://forum.vuejs.org/" class="nav-link" target="_blank" rel="noopener">论坛</a></li>
      <li><a href="https://chat.vuejs.org/" class="nav-link" target="_blank" rel="noopener">聊天室</a></li>
      <li><a href="https://events.vuejs.org/meetups/" class="nav-link" target="_blank" rel="noopener">聚会</a></li>
    </ul></li>
    <li><h4>工具</h4></li>
    <li>
      <ul>
        <li><a href="https://github.com/vuejs/vue-devtools" class="nav-link" target="_blank" rel="noopener">Devtools</a></li>
        <li><a href="https://cli.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue CLI</a></li>
        <li><a href="https://vue-loader.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Loader</a></li>
      </ul>
    </li>
    <li><h4>核心插件</h4></li>
    <li><ul>
      <li><a href="https://router.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue Router</a></li>
      <li><a href="https://vuex.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vuex</a></li>
      <li><a href="https://ssr.vuejs.org/zh/" class="nav-link" target="_blank" rel="noopener">Vue 服务端渲染</a></li>
    </ul></li>
    <li><h4>信息</h4></li>
    <li><ul>
      <li><a href="https://news.vuejs.org" class="nav-link" target="_blank" rel="noopener">周刊</a></li>
      <li><a href="https://github.com/vuejs/vue/projects/6" class="nav-link" target="_blank" rel="noopener">Roadmap</a></li>
      <li><a href="https://events.vuejs.org/" class="nav-link" target="_blank" rel="noopener">活动</a></li>
      <li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank" rel="noopener">Twitter</a></li>
      <li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank" rel="noopener">博客</a></li>
      <li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank" rel="noopener">工作</a></li>
    </ul></li>
  </ul>
</li>

<li>
  <a href="../guide/team.html" class="nav-link team">团队</a>
</li>
<li class="nav-dropdown-container resources">
  <a href="#" class="nav-link">资源列表</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../resources/partners.html" class="nav-link">合作伙伴</a></li>
    <li><a href="../../resources/themes.html" class="nav-link">主题</a></li>
    <li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
  </ul>
</li>

<!-- <li>
  <a href="/partners" class="nav-link ">Partners</a>
</li> -->
<li class="nav-dropdown-container support-vue">
  <a href="../../support-vuejs/index.html" class="nav-link">支持 Vue</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="../../support-vuejs/index.html#One-time-Donations" class="nav-link">一次性赞助</a></li>
    <li><a href="../../support-vuejs/index.html#Recurring-Pledges" class="nav-link">周期性赞助</a></li>
    <li><a href="https://www.smallsticker.com/%E8%B4%B4%E7%BA%B8/vue.html" rel="noopener" class="nav-link">贴纸</a></li>
    <li><a href="https://osholic.com/?utm_source=vue&amp;utm_medium=dropdown" rel="noopener" class="nav-link">周边</a></li>
    <li><a href="https://vue.threadless.com" target="_blank" rel="noopener" class="nav-link">T 恤商店</a></li>
  </ul>
</li>

<li class="nav-dropdown-container language">
  <a class="nav-link">多语言</a><span class="arrow"></span>
  <ul class="nav-dropdown">
    <li><a href="https://vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">English</a></li>
    <li><a href="https://jp.vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">日本語</a></li>
    <li><a href="https://ru.vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">Русский</a></li>
    <li><a href="https://kr.vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">한국어</a></li>
    <li><a href="https://br.vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">Português</a></li>
    <li><a href="https://fr.vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">Français</a></li>
    <li><a href="https://vi.vuejs.org/v2/cookbook/unit-testing-vue-components.html" class="nav-link" target="_blank" rel="noopener">Tiếng Việt</a></li>
  </ul>
</li>

<li><a href="https://github.com/vuejs/cn.vuejs.org/" target="_blank" class="nav-link contribute">参与翻译</a></li>

  </ul>
</div>

    
      <div id="main" class="fix-sidebar">
        
          
  

<div class="sidebar">
  <div class="sidebar-inner">
    
    <div class="list">
      <div id="sidebar-sponsors-special">
  <div class="main-sponsor">
    <span>特别赞助商</span>
    <div>
    <a href="http://www.dcloud.io/?hmsr=vuejsorg&amp;hmpl=&amp;hmcu=&amp;hmkw=&amp;hmci=" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/dcloud.gif" alt="">
    </a>
    </div>
    <div>
    <a href="https://youzan.github.io/vant?source=vuejsorg" target="_blank" rel="sponsored noopener" class="logo">
      <img src="../../images/vant.png" alt="">
    </a>
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-left">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->

      
        <h2>
          
          Cookbook<sup class="beta">beta</sup>
          
        </h2>
        <ul class="menu-root">
  
    
    
    <li>
      <a href="index.html" class="sidebar-link">介绍</a>
    </li>
  
    
    
    <li>
      <a href="adding-instance-properties.html" class="sidebar-link">添加实例属性</a>
    </li>
  
    
    
    <li>
      <a href="form-validation.html" class="sidebar-link">表单校验</a>
    </li>
  
    
    
    <li>
      <a href="editable-svg-icons.html" class="sidebar-link">可编辑的 SVG 图标系统</a>
    </li>
  
    
    
    <li>
      <a href="serverless-blog.html" class="sidebar-link">创建一个基于 CMS 的博客</a>
    </li>
  
    
    
    <li>
      <a href="unit-testing-vue-components.html" class="sidebar-link current">Vue 组件的单元测试</a>
    </li>
  
    
    
    <li>
      <a href="creating-custom-scroll-directives.html" class="sidebar-link">创建自定义滚动指令</a>
    </li>
  
    
    
    <li>
      <a href="debugging-in-vscode.html" class="sidebar-link">在 VS Code 中调试</a>
    </li>
  
    
    
    <li>
      <a href="using-axios-to-consume-apis.html" class="sidebar-link">使用 axios 访问 API</a>
    </li>
  
    
    
    <li>
      <a href="avoiding-memory-leaks.html" class="sidebar-link">避免内存泄漏</a>
    </li>
  
    
    
    <li>
      <a href="client-side-storage.html" class="sidebar-link">客户端存储</a>
    </li>
  
    
    
    <li>
      <a href="packaging-sfc-for-npm.html" class="sidebar-link">Packaging Vue Components for npm</a>
    </li>
  
    
    
    <li>
      <a href="dockerize-vuejs-app.html" class="sidebar-link">Dockerize Vue.js App</a>
    </li>
  
    
    
    <li>
      <a href="practical-use-of-scoped-slots.html" class="sidebar-link">Practical use of scoped slots with GoogleMaps</a>
    </li>
  
</ul>

      
    </div>
  </div>
</div>
<!--

<div id="sidebar-sponsors-platinum-right">
  <div class="main-sponsor">
    <span>白金赞助商</span>
    <div>
    <a href="https://vueschool.io/?utm_source=Vuejs.org&utm_medium=Banner&utm_campaign=Sponsored%20Banner&utm_content=V1" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vueschool.png" alt="VueSchool">
    </a>
    <a href="https://vehikl.com/" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/vehikl.png" alt="Vehikl">
    </a>
    <a href="https://www.nativescript.org/vue?utm_source=vue-js-org&utm_medium=website&utm_campaign=nativescript-awareness" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/nativescript.png" alt="NativeScript">
    </a>
    <a href="https://retool.com/?utm_source=sponsor&utm_campaign=vue" target="_blank" rel="sponsored noopener" class="logo">
      <img src="/images/retool.png" alt="Retool">
    </a>
    </div>
  </div>
  <a class="become-backer" href="/support-vuejs">
    成为赞助者
  </a>
</div>


-->


<div class="content cookbook with-sidebar ">
  
    
      
<div id="ad">
  <span style="float: right;">广告</span>
  <a href="https://time.geekbang.org/column/intro/216?code=mM%2FdqOPks0VQ7EkYGPNisoEpHDsb0ViHBXYa%2Fyg02k8%3D&amp;utm_term=SPoster" target="_blank" rel="sponsored noopener">
    <img src="../../images/geekbang-ad.jpg">
  </a>
  <!-- <a href="https://ke.qq.com/course/392130?saleToken=992600&from=pclink" target="_blank" rel="sponsored noopener">
    <img src="/images/tencent-ad.png">
  </a> -->
  <!-- <script
    async
    type="text/javascript"
    src="//cdn.carbonads.com/carbon.js?serve=CKYIK2QU&placement=vuejsorg"
    id="_carbonads_js">
  </script> -->
</div>


    
  
  
    <h1>Vue 组件的单元测试</h1>
  

  <div class="ad-pagetop">
  <a href="http://www.tp-shop.cn/index.php?http_referer=vuejs" target="_blank" rel="noopener noreferrer">
    <span class="name">TPshop</span>
    <span class="description">中国免费商城系统 - 搜豹商城系统 - 免费50小时Vue视频教程</span>
    <span class="action">立即查看 &gt;</span>
  </a>
</div>


  
    <h2 id="基本的示例"><a href="#%E5%9F%BA%E6%9C%AC%E7%9A%84%E7%A4%BA%E4%BE%8B" class="headerlink" title="基本的示例"></a>基本的示例</h2><p>单元测试是软件开发非常基础的一部分。单元测试会封闭执行最小化单元的代码，使得添加新功能和追踪问题更容易。Vue 的<a href="../guide/single-file-components.html">单文件组件</a>使得为组件撰写隔离的单元测试这件事更加直接。它会让你更有信心地开发新特性而不破坏现有的实现，并帮助其他开发者理解你的组件的作用。</p>
<p>这是一个判断一些文本是否被渲染的简单的示例：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"username"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
      <span class="hljs-attr">v-if</span>=<span class="hljs-string">"error"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"error"</span>
    &gt;</span>
      &#123;&#123; error &#125;&#125;
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Hello'</span>,
  data () &#123;
    <span class="hljs-keyword">return</span> &#123;
      <span class="hljs-attr">username</span>: <span class="hljs-string">''</span>
    &#125;
  &#125;,

  <span class="hljs-attr">computed</span>: &#123;
    error () &#123;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.username.trim().length &lt; <span class="hljs-number">7</span>
        ? <span class="hljs-string">'Please enter a longer username'</span>
        : <span class="hljs-string">''</span>
    &#125;
  &#125;
&#125;
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre>
<pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; shallowMount &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">'@vue/test-utils'</span>
<span class="hljs-keyword">import</span> Hello <span class="hljs-keyword">from</span> <span class="hljs-string">'./Hello.vue'</span>

test(<span class="hljs-string">'Hello'</span>, () =&gt; &#123;
  <span class="hljs-comment">// 渲染这个组件</span>
  <span class="hljs-keyword">const</span> wrapper = shallowMount(Hello)

  <span class="hljs-comment">// `username` 在除去头尾空格之后不应该少于 7 个字符</span>
  wrapper.setData(&#123; <span class="hljs-attr">username</span>: <span class="hljs-string">' '</span>.repeat(<span class="hljs-number">7</span>) &#125;)

  <span class="hljs-comment">// 确认错误信息被渲染了</span>
  expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBe(<span class="hljs-literal">true</span>)

  <span class="hljs-comment">// 将名字更新至足够长</span>
  wrapper.setData(&#123; <span class="hljs-attr">username</span>: <span class="hljs-string">'Lachlan'</span> &#125;)

  <span class="hljs-comment">// 断言错误信息不再显示了</span>
  expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBe(<span class="hljs-literal">false</span>)
&#125;)</code></pre>
<p>上述代码片段展示了如何基于 <code>username</code> 的长度测试一个错误信息是否被渲染。它展示了 Vue 组件单元测试的一般思路：渲染这个组件，然后断言这些标签是否匹配组件的状态。</p>
<h2 id="为什么要测试？"><a href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E6%B5%8B%E8%AF%95%EF%BC%9F" class="headerlink" title="为什么要测试？"></a>为什么要测试？</h2><p>组件的单元测试有很多好处：</p>
<ul>
<li>提供描述组件行为的文档</li>
<li>节省手动测试的时间</li>
<li>减少研发新特性时产生的 bug</li>
<li>改进设计</li>
<li>促进重构</li>
</ul>
<p>自动化测试使得大团队中的开发者可以维护复杂的基础代码。</p>
<h4 id="起步"><a href="#%E8%B5%B7%E6%AD%A5" class="headerlink" title="起步"></a>起步</h4><p><a href="https://github.com/vuejs/vue-test-utils" target="_blank" rel="noopener">Vue Test Utils</a> 是 Vue 组件单元测试的官方库。<a href="https://github.com/vuejs/vue-cli" target="_blank" rel="noopener">Vue CLI</a> 的 <code>webpack</code> 模板对 Karma 和 Jest 这两个测试运行器都支持，并且在 Vue Test Utils 的文档中有一些<a href="https://vue-test-utils.vuejs.org/zh/guides/" target="_blank" rel="noopener">引导</a>。</p>
<h2 id="实际的例子"><a href="#%E5%AE%9E%E9%99%85%E7%9A%84%E4%BE%8B%E5%AD%90" class="headerlink" title="实际的例子"></a>实际的例子</h2><p>单元测试应该：</p>
<ul>
<li>可以快速运行</li>
<li>易于理解</li>
<li>只测试<em>一个独立单元的工作</em></li>
</ul>
<p>我们在上一个示例的基础上继续构建，同时引入一个<a href="https://zh.wikipedia.org/wiki/%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95#%E5%B7%A5%E5%8E%82" target="_blank" rel="noopener">工厂函数 (factory function)</a>使得我们的测试更简洁更易读。这个组件应该：</p>
<ul>
<li>展示一个“Welcome to the Vue.js cookbook”的问候语</li>
<li>提示用户输入用户名</li>
<li>如果输入的用户名少于七个字符则展示错误信息</li>
</ul>
<p>让我们先看一下组件代码：</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"message"</span>&gt;</span>
      &#123;&#123; message &#125;&#125;
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    Enter your username: <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">v-model</span>=<span class="hljs-string">"username"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>
      <span class="hljs-attr">v-if</span>=<span class="hljs-string">"error"</span>
      <span class="hljs-attr">class</span>=<span class="hljs-string">"error"</span>
    &gt;</span>
      Please enter a username with at least seven letters.
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> &#123;
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Foo'</span>,

  data () &#123;
    <span class="hljs-keyword">return</span> &#123;
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Welcome to the Vue.js cookbook'</span>,
      <span class="hljs-attr">username</span>: <span class="hljs-string">''</span>
    &#125;
  &#125;,

  <span class="hljs-attr">computed</span>: &#123;
    error () &#123;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.username.trim().length &lt; <span class="hljs-number">7</span>
    &#125;
  &#125;
&#125;
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre>
<p>我们应该测试的内容有：</p>
<ul>
<li><code>message</code> 是否被渲染</li>
<li>如果 <code>error</code> 是 <code>true</code>，则 <code>&lt;div class=&quot;error&quot;&gt;</code> 应该展示</li>
<li>如果 <code>error</code> 是 <code>false</code>，则 <code>&lt;div class=&quot;error&quot;&gt;</code> 不应该展示</li>
</ul>
<p>我们的第一次测试尝试：</p>
<pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; shallowMount &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">'@vue/test-utils'</span>
<span class="hljs-keyword">import</span> Foo <span class="hljs-keyword">from</span> <span class="hljs-string">'./Foo.vue'</span>

describe(<span class="hljs-string">'Foo'</span>, () =&gt; &#123;
  it(<span class="hljs-string">'renders a message and responds correctly to user input'</span>, () =&gt; &#123;
    <span class="hljs-keyword">const</span> wrapper = shallowMount(Foo, &#123;
      <span class="hljs-attr">data</span>: &#123;
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Hello World'</span>,
        <span class="hljs-attr">username</span>: <span class="hljs-string">''</span>
      &#125;
    &#125;)

    <span class="hljs-comment">// 确认是否渲染了 `message`</span>
    expect(wrapper.find(<span class="hljs-string">'.message'</span>).text()).toEqual(<span class="hljs-string">'Hello World'</span>)

    <span class="hljs-comment">// 断言渲染了错误信息</span>
    expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBeTruthy()

    <span class="hljs-comment">// 更新 `username` 并断言错误信息不再被渲染</span>
    wrapper.setData(&#123; <span class="hljs-attr">username</span>: <span class="hljs-string">'Lachlan'</span> &#125;)
    expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBeFalsy()
  &#125;)
&#125;)</code></pre>
<p>上述代码有一些问题：</p>
<ul>
<li>单个测试断言了不同的事情</li>
<li>很难阐述组件可以处于哪些不同的状态，以及它该被渲染成什么样子</li>
</ul>
<p>接下来的示例从这几个方面改善了测试：</p>
<ul>
<li>每个 <code>it</code> 块只做一个断言</li>
<li>让测试描述更简短清晰</li>
<li>只提供测试需要的最小化数据</li>
<li>把重复的逻辑重构到了一个工厂函数中 (创建 <code>wrapper</code> 和设置 <code>username</code> 变量)</li>
</ul>
<p><em>更新后的测试</em>：</p>
<pre><code class="hljs js"><span class="hljs-keyword">import</span> &#123; shallowMount &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">'@vue/test-utils'</span>
<span class="hljs-keyword">import</span> Foo <span class="hljs-keyword">from</span> <span class="hljs-string">'./Foo'</span>

<span class="hljs-keyword">const</span> factory = <span class="hljs-function">(<span class="hljs-params">values = &#123;&#125;</span>) =&gt;</span> &#123;
  <span class="hljs-keyword">return</span> shallowMount(Foo, &#123;
    data () &#123;
      <span class="hljs-keyword">return</span> &#123;
        ...values
      &#125;
    &#125;
  &#125;)
&#125;

describe(<span class="hljs-string">'Foo'</span>, () =&gt; &#123;
  it(<span class="hljs-string">'renders a welcome message'</span>, () =&gt; &#123;
    <span class="hljs-keyword">const</span> wrapper = factory()

    expect(wrapper.find(<span class="hljs-string">'.message'</span>).text()).toEqual(<span class="hljs-string">"Welcome to the Vue.js cookbook"</span>)
  &#125;)

  it(<span class="hljs-string">'renders an error when username is less than 7 characters'</span>, () =&gt; &#123;
    <span class="hljs-keyword">const</span> wrapper = factory(&#123; <span class="hljs-attr">username</span>: <span class="hljs-string">''</span>  &#125;)

    expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBeTruthy()
  &#125;)

  it(<span class="hljs-string">'renders an error when username is whitespace'</span>, () =&gt; &#123;
    <span class="hljs-keyword">const</span> wrapper = factory(&#123; <span class="hljs-attr">username</span>: <span class="hljs-string">' '</span>.repeat(<span class="hljs-number">7</span>)  &#125;)

    expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBeTruthy()
  &#125;)

  it(<span class="hljs-string">'does not render an error when username is 7 characters or more'</span>, () =&gt; &#123;
    <span class="hljs-keyword">const</span> wrapper = factory(&#123; <span class="hljs-attr">username</span>: <span class="hljs-string">'Lachlan'</span>  &#125;)

    expect(wrapper.find(<span class="hljs-string">'.error'</span>).exists()).toBeFalsy()
  &#125;)
&#125;)</code></pre>
<p>注意事项：</p>
<p>在一开始，工厂函数将 <code>values</code> 对象合并到了 <code>data</code> 并返回了一个新的 <code>wrapper</code> 实例。这样，我们就不需要在每个测试中重复 <code>const wrapper = shallowMount(Foo)</code>。另一个好处是当你想为更复杂的组件在每个测试中伪造或存根一个方法或计算属性时，你只需要声明一次即可。</p>
<h2 id="额外的上下文"><a href="#%E9%A2%9D%E5%A4%96%E7%9A%84%E4%B8%8A%E4%B8%8B%E6%96%87" class="headerlink" title="额外的上下文"></a>额外的上下文</h2><p>上述的测试是非常简单的，但是在实际情况下 Vue 组件常常具有其它你想要测试的行为，诸如：</p>
<ul>
<li>调用 API</li>
<li>为 <code>Vuex</code> 的 store，commit 或 dispatch 一些 mutation 或 action</li>
<li>测试用户交互</li>
</ul>
<p>我们在 Vue Test Utils 的<a href="https://vue-test-utils.vuejs.org/zh/guides/" target="_blank" rel="noopener">教程</a>中提供了更完整的示例展示这些测试。</p>
<p>Vue Test Utils 及庞大的 JavaScript 生态系统提供了大量的工具促进 100% 的测试覆盖率。单元测试只是整个测试金字塔中的一部分。其它类型的测试还包括 e2e (端到端) 测试、快照比对测试等。单元测试是最小巧也是最简单的测试——它们通过隔离单个组件的每一个部分，来在最小工作单元上进行断言。</p>
<p>快照比对测试会保存你的 Vue 组件的标记，然后比较每次新生成的测试运行结果。如果有些东西改变了，开发者就会得到通知，并决定这个改变是刻意为之 (组件更新时) 还是意外发生的 (组件行为不正确)。</p>
<p>端到端测试致力于确保组件的一系列交互是正确的。它们是更高级别的测试，例如可能会测试用户是否注册、登录以及更新他们的用户名。这种测试运行起来会比单元测试和快照比对测试慢一些。</p>
<p>单元测试中开发的时候是最有用的，即能帮助开发者思考如何设计一个组件或重构一个现有组件。通常每次代码发生变化的时候它们都会被运行。</p>
<p>高级别的测试，诸如端到端测试，运行起来会更慢很多。这些测试通常只在部署前运行，来确保系统的每个部分都能够正常的协同工作。</p>
<p>更多测试 Vue 组件的知识可翻阅核心团员 <a href="https://eddyerburgh.me/" target="_blank" rel="noopener">Edd Yerburgh</a> 的书<a href="https://www.manning.com/books/testing-vuejs-applications" target="_blank" rel="noopener">《测试 Vue.js 应用》</a>。</p>
<h2 id="何时避免这个模式"><a href="#%E4%BD%95%E6%97%B6%E9%81%BF%E5%85%8D%E8%BF%99%E4%B8%AA%E6%A8%A1%E5%BC%8F" class="headerlink" title="何时避免这个模式"></a>何时避免这个模式</h2><p>单元测试是任何正经的应用的重要部分。一开始，当你对一个应用的愿景还不够清晰的时候，单元测试可能会拖慢开发进度，但是一旦你的愿景建立起来并且有真实的用户对这个应用产生兴趣，那么单元测试 (以及其它类型的自动化测试) 就是绝对有必要的了，它们会确保基础代码的可维护性和可扩展性。</p>

  
  
  <div class="footer">
      <script src="https://m.servedby-buysellads.com/monetization.js" type="text/javascript"></script>
<div id="bsa-native"></div>
<script>
_bsa.init('custom', 'CKYD62QM', 'placement:vuejsorg',
  {
    target: '#bsa-native',
    template: '<a class="native-box" href="##statlink##"><div class="native-sponsor">Sponsor</div><div class="native-text"><strong>##company##</strong> — ##description##</div></a>'
  }
);
</script>


    发现错误？想参与编辑？
    <a href="https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/cookbook/unit-testing-vue-components.md" rel="noopener" target="_blank">
      在 GitHub 上编辑此页！
    </a>
  </div>
</div>

        
      </div>
      <script src="../../js/smooth-scroll.min.js"></script>
    

    <!-- main custom script for sidebars, version selects etc. -->
    <script src="../../js/css.escape.js"></script>
    <script src="../../js/common.js"></script>

    <!-- search -->
    <link href="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="../../css/search.css">
    <script src="https://code.bdstatic.com/npm/docsearch.js@1.5.0/dist/cdn/docsearch.min.js"></script>
    <script>
    [
      '#search-query-nav',
      '#search-query-sidebar',
      '#search-query-menu'
    ].forEach(function (selector) {
      if (!document.querySelector(selector)) return
      // search index defaults to v2
      var match = window.location.pathname.match(/^\/(v\d+)/)
      var version = match ? match[1] : 'v2'
      docsearch({
      appId: 'BH4D9OD16A',
      apiKey: '5638280abff9d207417bb03be05f0b25',
      indexName: 'vuejs_cn2',
      inputSelector: selector,
      algoliaOptions: { facetFilters: ["version:" + version] },
      autocompleteOptions: { hint: false, appendTo: 'body'}
      })
    })
    </script>
  </body>
</html>
